#ifndef _DB_UPLOAD_H_
#define _DB_UPLOAD_H_

#include <string>
#include <vector>
#include <sstream>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include "../common/mysql_wrapper.hpp"

struct STUploadTable
{
	unsigned int m_uiID;
	std::string m_sName;
	std::string m_sMd5;
	std::string m_sUrl;
};

class CUploadTable : public CMysqlWrapper
{
public:
	CUploadTable(){}
	virtual ~CUploadTable(){}

	bool getUrlByFileName(const std::string& name, std::string& store)
	{
		std::stringstream ss;
		ss<<"select FuiID, FsName, FsMd5, FsUrl from t_upload where FsName = '"<<name<<"' limit 1";
		std::vector<STUploadTable> sts;
		if(excuteSelect(ss.str(), boost::bind(&CUploadTable::store<std::vector<STUploadTable> >, this, boost::ref(sts), _1, _2)) == 0)
		{
			if(sts.size()>0)
			{
				store = sts[0].m_sUrl;
				return true;
			}
		}
		return false;
	}

	bool getUrlByMd5(const std::string& md5, std::string& store)
	{
		std::stringstream ss;
		ss<<"select FuiID, FsName, FsMd5, FsUrl from t_upload where FsMd5 = '"<<md5<<"' limit 1";
		std::vector<STUploadTable> sts;
		if(excuteSelect(ss.str(), boost::bind(&CUploadTable::store<std::vector<STUploadTable> >, this, boost::ref(sts), _1, _2)) == 0)
		{
			if(sts.size()>0)
			{
				store = sts[0].m_sUrl;
				return true;
			}
		}
		return false;
	}

	int create(const STUploadTable& st)
	{
		std::stringstream ss;
		ss<<"insert into t_upload(FsName, FsMd5, FsUrl) value ("
			<<"'"<<st.m_sName<<"',"
			<<"'"<<st.m_sMd5<<"',"
			<<"'"<<st.m_sUrl<<"'"
			<<")";
		return excute(ss.str());
	}

	template<class T>
	void store(T& store, MYSQL_ROW row, unsigned long *lengths)
	{
		STUploadTable st;
		st.m_uiID = boost::lexical_cast<unsigned int>(std::string(row[0], lengths[0]));
		st.m_sName = std::string(row[1], lengths[1]);
		st.m_sMd5 = std::string(row[2], lengths[2]);
		st.m_sUrl = std::string(row[3], lengths[3]);
		store.push_back(st);
	}
};

#endif //_DB_UPLOAD_H_